package per.zx;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * @author zhengxin
 * @date 2021/7/1 22:31
 * @description Unsafe类
 */
public class TestUnSafe {

/*   //无法获取：java.lang.ExceptionInInitializerError
    // 获取 UnSafe 对象
    static final Unsafe unsafe = Unsafe.getUnsafe();
    // 用于记录 state 在内存类 TestUnSafe 中的偏移值
    static final long stateOffset;
    private volatile long state = 0;
    static {
        try {
            stateOffset = unsafe.objectFieldOffset(TestUnSafe.class.getDeclaredField("state"));
        } catch (Exception e) {
            e.printStackTrace();
            throw new Error(e);
        }
    }*/

    // 使用反射获取
    static final Unsafe unsafe;
    static final long stateOffset;
    private volatile long state = 0;
    static {
        try {
            Field field = Unsafe.class.getDeclaredField("theUnsafe");

            field.setAccessible(true);
            unsafe = (Unsafe) field.get(null);

            stateOffset = unsafe.objectFieldOffset(TestUnSafe.class.getDeclaredField("state"));
        } catch (Exception e) {
            e.printStackTrace();
            throw new Error(e);
        }
    }


    public static void main(String[] args) {
        TestUnSafe testUnSafe = new TestUnSafe();
        System.out.println(unsafe.compareAndSwapInt(testUnSafe, stateOffset, 0, 1));

    }
}
